<!--
* description: 备件奖励单网点确认
* author: xiaochengzuan
* createdDate: 2021-1-22
-->

<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :callback-obj="callbackObj"
    />

    <edit
      :key="editPopupsKey"
      :dynamic-edit-row-data="editRowData"
      :popups-visible.sync="editPopupsVisible"
      :popups-state="editPopupsState"
    />
  </div>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import api from '@/api/pa/financialManagement'

export default {
  name: 'ConfirmationOfSparePartsRewardList',

  components: {
    OneTableTemplate,
    Edit: () => import('./edit')
  },

  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path

    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      editPopupsVisible: false,
      editRowData: {},
      // 网格查询API配置对象
      apiConfig: api.queryBonusConfrimPage,

      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'search',
          clickEvent: () => this.queryTable(1),
          text: this.$t('sys.button.query'), // 查询
          position: 'right',
          fuzzySearch: true
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.reset(),
          text: this.$t('sys.button.reset'),
          position: 'right' // 重置
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'reject',
          icon: 'iconfont icon-reject',
          clickEvent: () => this.edit(),
          text: '申诉',
          position: 'left',
          disabled: true
        },
        {
          compKey: 'btnKey4',
          size: 'small',
          name: 'adopt',
          icon: 'iconfont icon-adopt',
          clickEvent: () => this.confirm(),
          text: '确认',
          position: 'left',
          disabled: true
        },
        {
          compKey: 'btnKey5',
          size: 'small',
          name: 'export',
          clickEvent: () => this.exportExcel(),
          text: this.$t('sys.button.export'),
          position: 'left'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '网点编码：',
              codeField: 'dlrCode',
              component: () => import('@/components/pa/dlrCode'),
              type: 'inputText',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey2',
              labelName: '网点名称：',
              codeField: 'dlrShortName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              disabled: true
            },
            {
              compKey: 'compKey3',
              labelName: '奖励种类：',
              codeField: 'bonusTypeId',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'bonusTypeId,bonusTypeName',
              customObj: {
                api: api.fqueryBonusTypes
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '奖励项目：',
              codeField: 'bonusItemId',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'bonusItemId,bonusItemName',
              customObj: {
                api: api.fqueryBonusItems,
                listQuery: {
                  bonusItemId: ''
                },
                selectType: '1'
              },
              type: 'dropdownList',
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '奖励单号：',
              codeField: 'bonusOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: false
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'dlrId',
              label: '网点ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'bonusTypeId',
              label: '奖励种类ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'bonusItemId',
              label: '奖励项目ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'bonusOrderId',
              label: '奖励单ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'dlrCode',
              label: '网点编码',
              width: 140
            },
            {
              prop: 'dlrShortName',
              label: '网点名称'
            },
            {
              prop: 'bonusOrderCode',
              label: '奖励单号',
              width: 140
            },
            {
              prop: 'bonusTypeName',
              label: '奖励种类',
              width: 140
            },
            {
              prop: 'bonusItemName',
              label: '奖励项目',
              width: 140
            },
            {
              prop: 'bonusAmount',
              label: '奖励金额'
            },
            {
              prop: 'creator',
              label: '创建人'
            },
            {
              prop: 'createdDate',
              label: '创建时间',
              width: 140
            },
            {
              prop: 'bonusStatusCn',
              label: '审核状态'
            },
            {
              prop: 'bigAreaCode',
              label: '业务审核意见',
              width: 140
            },
            {
              prop: 'bigAreaCode',
              label: '财务审核意见',
              width: 140
            }

          ],

      // 表单查询数据
      formField: this.$utils.getFormField(this, {
        dlrCode: '',
        dlrShortName: '',
        bonusOrderCode: '',
        bonusTypeName: '',
        bonusItemName: '',
        dlrId: '',
        bonusTypeId: '',
        bonusItemId: '',
        bonusOrderId: '',
        updateControlId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      callbackObj: {
        // 当选择项发生变化时会触发该事件（多选时）
        onCheckSelectChange: (selection) => {
          this.selectData = selection

          this.handleSelectionChange(selection)
        }
      }
    }
  },

  mounted() {
    // 列表查询
    this.queryTable(1)
  },

  methods: {
    // 获取数据
    edit() {
      this.editPopupsState = 'edit'
      this.editPopupsVisible = true
    },
    // 通过
    confirm() {
      // const that = this
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: api.editBonusConfirm,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          bonusOrderStatus: this.selectData.reduce((pre, cur, idx) => {
            const { bonusOrderId,
              updateControlId } = cur
            pre.push({ bonusOrderId,
              updateControlId,
              appealOpinions: this.formField.appealOpinions
            })
            return pre
          }, [])
        }
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then(response => {
        if (response.result === '1') {
          this.$message({
            message: '操作成功!',
            type: 'success',
            duration: 1000
          })
          this.$nextTick(() => {
            this.$refs.multipleTable.queryTable(1)
          })
        } else {
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },

    // 导出
    exportExcel() {
      const fileName = this.$utils.fileNameWithTime('备件奖励单网点确认.xlsx')
      this.$requestAPI({
        apiUrl: api.exportBonusOrderConfirm.APIUrl,
        variables: { dataType: 'excel' }
      }).then(res => {
        this.$utils.downloadFile(res, fileName)
      }).catch(err => {
        console.log(err)
      })
    },

    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    }
  }
}
</script>
